//
//  UIView+extension.swift
//  MM
//
//  Created by 李成明 on 2021/12/30.
//

import Foundation
import UIKit

private let toastLabel: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 18)
    label.backgroundColor = .black
    label.textColor = .white
    label.textAlignment = .center
    label.layer.masksToBounds = true
    label.layer.cornerRadius = 8
    return label
}()

extension UIView {
    func addsubViews(_ views: [UIView]) {
        views.forEach { view in
            self.addSubview(view)
        }
    }
    
    func showToast(text: String, autoDisMiss: Bool = true) {
        toastLabel.removeFromSuperview()
        toastLabel.text = text
        addSubview(toastLabel)
        
        var textSize = toastLabel.sizeThatFits(CGSize(width: kScreenWidth, height: CGFloat.greatestFiniteMagnitude))
        textSize = CGSize(width: textSize.width + 16, height: textSize.height + 8)
        let viewWidth = bounds.size.width
        let viewHeight = bounds.size.height
        toastLabel.frame = CGRect(x: (viewWidth - textSize.width)/2, y: (viewHeight - textSize.height)/2, width: textSize.width, height: textSize.height)
        addSubview(toastLabel)
        
        if autoDisMiss {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.dismissToast()
            }
        }
    }
    
    func dismissToast() {
        toastLabel.frame = CGRect.zero
        toastLabel.removeFromSuperview()
    }
}
